﻿namespace OverStore.Configuration.Storage
{
    using System;
    using OverStore.Configuration.Validation;
    using OverStore.Exceptions.Configuration;
    using OverStore.Runtime.OverStoreContext;
    using OverStore.Runtime.Storage;

    /// <summary>
    /// Contains configuration parameters allows to create instances.
    /// </summary>
    public sealed class AdoNetScriptConfiguration : AdoNetCommandBaseConfiguration, ISupportValidation
    {
        /// <summary>
        /// Gets or sets the first script command.
        /// </summary>
        /// <result>The first command.</result>
        public AdoNetCommandBaseConfiguration FirstCommand { get; set; }

        /// <summary>
        /// Gets or sets the second script command.
        /// </summary>
        /// <result>The second command.</result>
        public AdoNetCommandBaseConfiguration SecondCommand { get; set; }

        /// <summary>
        /// Gets or sets the resut composition mode defines how results of first and second command composes into one result of script command.
        /// </summary>
        /// <result>The resut composition mode.</result>
        public ResultComposition ResultComposition { get; set; }

        /// <summary>
        /// Perform component validation. Method should validate only
        /// component configuration itself, not sub components.
        /// If configuration is valid, null result should returns.
        /// </summary>
        /// <returns>
        ///     <see cref="T:OverStore.Configuration.ValidationResults"/> describes errors found in component configuration.
        /// </returns>
        public ValidationResult Validate()
        {
            return new ValidationResult(this)
                .AddError(FirstCommand == null, "Fist Command is missing.")
                .AddError(SecondCommand == null, "Second Command is missing.");
        }

        /// <summary>
        /// When overriden in derived classes, creates new instance of class inherited from <see cref="AdoNetCommandBase"/>.
        /// </summary>
        public override AdoNetCommandBase CreateCommand(IOverStoreContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (FirstCommand == null)
                throw this.ConfigurationException("First Command is missing.");
            if (SecondCommand == null)
                throw this.ConfigurationException("Second Command is missing.");
            return new AdoNetScript(FirstCommand.CreateCommand(context), SecondCommand.CreateCommand(context), ResultComposition);
        }
    }
}
